<?php

namespace App\Controllers;

use Windward\Core\Response\Plain as PlainResponse;

class Audit extends Base
{

    public $model = null;

    public function __construct(\Windward\Core\Container $container)
    {
        parent::__construct($container);
        $this->model = $container->model('Account');
    }

    /**
     * 审核用户个人信息
     */
    public function profileAction()
    {
        $clubUserId = intval($this->request->getQuery('club_user_id'));
        if (!$clubUserId) {
            $this->redirect('/user/index');
        }
        $_SESSION['audit_club_user_id'] = $clubUserId;
        $auditUser = $_SESSION['audit_admin'];
        if (!$auditUser) {
            $this->redirect('/audit/login');
        }
        //如果是认证专员，则显示该用户的待认证信息，否则显示错误页面
        if ($auditUser['role'] == 3) {
            $userModel = $this->container->model('User');
            $authinfo = $userModel->userAuthInfo($clubUserId);
            $user = $userModel->get('tb_club_user', '*', ['id' => $clubUserId, 'deleted' => 0]);
            $response = new \Windward\Core\Response\Smarty($this->container);
            $response->setTpl("User/profile");
            $response->set('flag', 1);
            $response->set('userId', $clubUserId);
            $response->set('authinfo', $authinfo);
            $response->set('user', $user);
            $response->set('title', '认证审核');
            return $response;
        } else {
            $this->redirect('/user/index');
        }
    }

    public function loginAction()
    {
        if($_SESSION['audit_admin']){
            $this->redirect('/audit/profile?club_user_id=' . $_SESSION['audit_club_user_id']);
        }
        $errors = [];
        $data = $this->request->getPost("data");
        if ($this->request->isComplete()) {
            if ($this->model->validLogin($data, $errors)) {
                if ($user = $this->model->login($data, $errors)) {
                    $_SESSION['audit_admin'] = $user;
                    $this->redirect('/audit/profile?club_user_id=' . $_SESSION['audit_club_user_id']);
                }
            }
            if ($errors) {
                $errors = array_column($errors, 'msg');
            }
            $this->view->assign('errors', $errors);
            $this->view->assign('data', $data);
        }
        $response = new \Windward\Core\Response\Smarty($this->container);
        $response->setTpl('User/login');
        $response->set('title','登录');
        return $response;
    }

    /**
     * 认证
     */
    public function changeStatusAction()
    {
        $post = $this->request->getPost();
        $error = 'auth_error';
        $userModel = $this->container->model('User');
        if ($userModel->changeStatus($post, $error) === false) {
            return $this->error($error);
        }
        return $this->success();
    }

}
